<?php

namespace Home\Controller;

/**
 * @description 上传文件中心控制器
 * @modify songanwei 2016-01-08
 */
class FileController extends \Home\Controller\ParentController {

    protected function _initialize() {
        $this->checkLogin();
    }

    /**
     * @description  异步上传文件
     * @modify songanwei 2016-01-08
     * @modify trainyao 2016-04-28 文件上传公共入口增加权限管理
     */
    public function upload() {
        $param = I('request.');
        $configName = isset($param['config']) ? $param['config'] : 'default';
        $config_info = C($configName);
        
        // 检测文件大小
        $fileSizes = array_column($_FILES, 'size');
        foreach ($fileSizes as $fileSize) {
            if ($fileSize > $config_info['maxSize']) {
                returnJson(500, 511);
                return;
            }
        }
        unset($fileSize);

        // 不同地方上传图片,权限校验
        if (!in_array($configName, array('user', 'default', 'publicLink'))) {
            $validateRule = array(
                'hotel' => 'notnull,notempty,id',
            );
            $validateUtil = new \Org\Util\Validate();
            $validatePass = $this->ajaxValidateReturn($validateUtil, $param, $validateRule);
            if (empty($validatePass)) {
                return;
            }
            $hotelId = $param['hotel'];
            // 校验权限,目前只有超级管理员能访问
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $adminAuthorityLogic->check($hotelId);
        }

        $config = array(
            'maxSize' => $config_info['maxSize'],
            'rootPath' => $config_info['rootPath'],
            'savePath' => $config_info['savePath'],
            'exts' => $config_info['exts'],
            'subName' => array('date', 'Ymd'),
        );

        $upload = new \Think\Upload($config);
        $info = $upload->upload();
        if (!$info) {
            returnJson(500, 511, $upload->getError());
        }
        $filename = '/Uploads/' . $info['file']['savepath'] . $info['file']['savename'];
        returnJson(200, 200, array('filename' => $filename));
    }
}
